﻿// ********************************************************************************************************
// <copyright file="Main.cs" company="TopX Geo-ICT">
//     Copyright (c) 2012 TopX Geo-ICT. All rights reserved.
// </copyright>
// ********************************************************************************************************
// The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License"); 
// you may not use this file except in compliance with the License. You may obtain a copy of the License at 
// http:// www.mozilla.org/MPL/ 
// Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF 
// ANY KIND, either express or implied. See the License for the specificlanguage governing rights and 
// limitations under the License. 
// 
// The Initial Developer of this version is Paul Meems.
// 
// Contributor(s): (Open source contributors should list themselves and their modifications here). 
// Change Log: 
// Date           Changed By      Notes
// 29 March 2012  Jeen de Vegt    Inital coding
// ********************************************************************************************************
namespace TableEditorNew
{
    using System;
    using System.Collections.Generic;
    using System.Windows.Forms;
    using MapWindow.Interfaces;
    using MapWinGIS;
    using TableEditorNew.BO;
    using TableEditorNew.Forms;

    /// <summary>
    ///   This is the start of the plug-in. In here all methods of the IPlugin interface can be implemented.
    /// </summary>
    public class Main : PluginBase
    {
        /// <summary>Change this to your own address</summary>
        private const string ReportEmailaddress = "Bontepaarden@gmail.com";

        /// <summary>The stack with the toolbuttons</summary>
        private readonly Stack<string> addedToolbuttons = new Stack<string>();

        /// <summary>The name of your button. This need to be a constant</summary>
        private const string MyButton = "Table Editor";

        /// <summary>The name of the toolbar</summary>
        private string toolbarName;

        /// <summary>Reference to the frmTableEditor</summary>
        private frmTableEditor tableEditor;

        /// <summary>This event is called when a plugin is loaded or turned on in the MapWindow.</summary>
        public override void Initialize()
        {
            try
            {
                // Create toolbar:
                this.toolbarName = this.Author;
                this.CreateToolbar();
            }
            catch (Exception ex)
            {
                this.App.ShowErrorDialog(ex, ReportEmailaddress);
            }
        }

        /// <summary>This method is called when a plugin is unloaded. The plugin should remove all toolbars, buttons and menus that it added.</summary>
        public override void Terminate()
        {
            /*
            // Close form:
            var inputform = Controls.Main.GetActivatedWindow<Inputform>(new IntPtr(this.ParentHandle), false);
            if (inputform != null)
            {
                inputform.Dispose();
            }
            */

            // Remove toolbar:
            if (this.addedToolbuttons != null)
            {
                // Unloads the buttons in reverse order
                while (this.addedToolbuttons.Count > 0)
                {
                    this.App.Toolbar.RemoveButton(this.addedToolbuttons.Pop());
                }

                // If all buttons are removed, remove toolbar as well:
                if (this.App.Toolbar.NumToolbarButtons(this.toolbarName) == 0)
                {
                    this.App.Toolbar.RemoveToolbar(this.toolbarName);
                }
            }
        }

        /// <summary>Occurs when a user clicks on a toolbar button or menu item.</summary>
        /// <param name = "itemName">The name of the item clicked on.</param>
        /// <param name = "handled">Reference parameter.  Setting Handled to true prevents other plugins from receiving this event.</param>
        public override void ItemClicked(string itemName, ref bool handled)
        {
            try
            {
                switch (itemName)
                {
                    case MyButton:
                        handled = true;

                        if (this.tableEditor == null)
                        {
                            BOShapeFile sf = this.CreateBOShapeFile();
                            if (sf != null)
                            {
                                this.tableEditor = new frmTableEditor(sf, new BOMapWindow(App));

                                this.tableEditor.FormClosing += new FormClosingEventHandler(this.tableEditor_FormClosing);

                                this.tableEditor.Show();

                                this.tableEditor.InitForm();
                            }
                            else
                            {
                                MessageBox.Show("Selected Layer is not a shapefile.");
                            }
                        }

                        break;
                }
            }
            catch (Exception ex)
            {
                this.App.ShowErrorDialog(ex, ReportEmailaddress);
            }
        }

        /// <summary>Occurs when the editor-form is closing.</summary>
        /// <param name = "sender">The sender of the event.</param>
        /// <param name = "e">The arguments.</param>
        public void tableEditor_FormClosing(object sender, FormClosingEventArgs e)
        {
            this.tableEditor.Dispose();
            this.tableEditor = null;
        }

        /// <summary>Updates the selected shapes in grid equal to the map.</summary>
        /// <param name = "handle">The handle.</param>
        /// <param name = "selectInfo">Additional info.</param>
        public override void ShapesSelected(int handle, SelectInfo selectInfo)
        {
            if (this.tableEditor != null)
            {
                this.tableEditor.SetSelected();
            }
        }

        /// <summary>New layer selected.</summary>
        /// <param name = "handle">The handle.</param>
        public override void LayerSelected(int handle)
        {
            if (this.tableEditor != null)
            {
                this.tableEditor.CheckAndSaveChanges();

                eLayerType layerType = this.App.Layers[handle].LayerType;

                if (layerType != eLayerType.LineShapefile && layerType != eLayerType.PointShapefile
                    && layerType != eLayerType.PolygonShapefile)
                {
                    this.tableEditor.Close();
                }
                else
                {
                    BOShapeFile boShapeFile = this.CreateBOShapeFile();
                    if (boShapeFile == null)
                    {
                        MessageBox.Show(this.tableEditor, "Selected layer is not a shapefile");
                    }
                    else
                    {
                        this.ClearSelections();

                        this.tableEditor.boShapeFile = boShapeFile;
                        this.tableEditor.SetDataGrid();
                    }
                }
            }
        }

        /// <summary>Clears all selections.</summary>
        private void ClearSelections()
        {
            for (int i = 0; i < App.Layers.NumLayers; i++)
            {
                App.Layers[i].ClearSelection();
            }
        }

        /// <summary>Create the toolbar</summary>
        private void CreateToolbar()
        {
            // Add toolbar with buttons:
            var t = this.App.Toolbar;
            t.AddToolbar(this.toolbarName);

            // First button:
            var b = t.AddButton(MyButton, this.toolbarName, string.Empty, string.Empty);
            b.BeginsGroup = true;
            b.Tooltip = "Table Editor";
            b.Category = this.toolbarName;
            b.Text = "Table";

            b.Picture = Properties.Resources.table_editor;

            // Save to remove it easily on terminate:
            this.addedToolbuttons.Push(MyButton);
        }

        /// <summary>Creates the BOShapeFile.</summary>
        /// <returns>The BOShapeFile</returns>
        private BOShapeFile CreateBOShapeFile()
        {
            BOShapeFile boShapeFile = null;

            Shapefile shapeFile = App.Layers[App.Layers.CurrentLayer].GetObject() as Shapefile;
            if (shapeFile != null)
            {
                boShapeFile = new BOShapeFile
                    {
                        ShapeFile = shapeFile, 
                        ShapefileName = this.App.Layers[this.App.Layers.CurrentLayer].Name 
                    };
            }

            return boShapeFile;
        }
    }
}
